package com.batchengine.task;

import com.batchengine.DataAdapter;
import com.batchengine.Definitions;
import com.batchengine.util.EnvUtil;
import com.batchengine.util.LoggingFactory;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Map;
import java.util.TreeMap;

import static com.batchengine.Definitions.DataAdapter.FILE;
import static com.batchengine.task.TaskUtil.getRecurringJobMap;
import static java.lang.Long.parseLong;
import static java.lang.String.format;

/**
 * Created by  solutions
 * Author: sunil.incubator@yahoo.com
 * Date: Aug 9, 2009
 */
public abstract class RecurringJobParser {

    private static final Logger logger = LoggingFactory.createLogger();

    private RecurringJobParser() {

    }

    public static RecurringJobParser getTaskDataParser(DataAdapter adapter) {
        assert null != adapter;
        return new FileParser();
    }

    public abstract Definitions.DataAdapter adapterType();

    public abstract Map<Long, RecurringJob> loadRecurringJobMap();

    /**
     * This class parses the line of the format
     * #jobid,taskid, task-name,min workers,max workers,sleep time
     */
    private static class FileParser extends RecurringJobParser {

        @Override
        public Definitions.DataAdapter adapterType() {
            return FILE;
        }

        public Map<Long, RecurringJob> loadRecurringJobMap() {

            Map<Long, RecurringJob> taskMap = new TreeMap<Long, RecurringJob>();

            try {

                BufferedReader reader = null;
                String line;
                reader = new BufferedReader(new FileReader(String.format("%s/recurringjobs.conf", EnvUtil.getConfFolderLocation())));
                while(null != (line = reader.readLine())) {

                    if(line.startsWith("#") || 0 == line.trim().length()) {
                        continue;
                    }
                    String[] strings = line.split(",");
                    if(6 != strings.length || !line.endsWith(";")) {
                        logger.error(format("#not able to parse task config line %s", line));
                        continue;
                    }

                    try {

                        long taskId = parseLong(strings[0]);
                        RecurringJob job = new RecurringJob(taskId);
                        job.setId(taskId);

                        taskId = parseLong(strings[1]);
                        TaskInfo taskInfo = TaskParser.getTaskDataParser(DataAdapter.FILE).getTaskConfigurationMap().get(taskId);
                        job.setTaskInfo(taskInfo);

                        job.setInstanceName(strings[2]);
                        job.setMinWorkers(Integer.parseInt(strings[3]));
                        job.setMaxWorkers(Integer.parseInt(strings[4]));

                        String delay = strings[5];
                        String[] delayArry = delay.split(":");
                        job.setDelay(Integer.parseInt(delayArry[0]));
                        if(null != delayArry[1] && 1 < delayArry[1].trim().length()) {
                            job.setDelayParam(Definitions.DelayParam.valueOf(delayArry[1].substring(0, delayArry[1].lastIndexOf(";"))));
                        }
                        taskMap.put(taskId, job);
                    } catch(Exception e) {
                        logger.error(format("#not able to parse task config line %s", line), e);
                    }
                }
            } catch(Exception e) {
                logger.error(format("error@TaskParser#%s#getTaskConfigurationMap", adapterType()));
            }
            return taskMap;
        }
    }

    public static void main(String[] args) {

        Map<Long, RecurringJob> map = getRecurringJobMap();
        for(Long o : map.keySet()) {
            System.out.println(map.get(o));
        }
    }
}
